import sys
from pathlib import Path

from loguru import logger

from app.core.config import CoreSettings


def register_logger(config: CoreSettings):
    """
    注册日志到FastAPI应用
    """
    logger.remove()

    # 添加自定义日志配置
    logger.add(
        sys.stderr,
        format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level=config.logging.level.upper(),
        backtrace=True,
        diagnose=True
    )
    if config.logging.path:
        log_dir = Path(config.logging.path)
        log_dir.mkdir(parents=True, exist_ok=True)
        # 添加文件日志
        logger.add(
            str(log_dir / "app.log"),
            rotation=config.logging.rotation,
            retention=config.logging.retention,
            compression="zip",
            level=config.logging.level.upper(),
        )
